<?php

namespace app\controller;

use app\model\TorrentBank;
use app\model\TorrentCache;
use support\Request;
use app\model\User as UserModel;
use app\model\Download as DownloadModel;
use app\model\Sites as SiteModel;
use app\model\SystemLog as SystemLogModel;
use app\model\Crontab as CrontabModel;

class IndexController
{

    protected $noNeedLogin = [];
    public function index()
    {
        //首先获取站点表和下载器表所有数据
        $systemlogs = SystemLogModel::select();
        $sites = SiteModel::select();
        $downloads = DownloadModel::select();
        $torrentscache = TorrentCache::select();
        $crontabs = CrontabModel::select();

        // // 系统日志错误数
        $systemLogsData = [
            'error' => $systemlogs->where("type",'error')->count(),
            'success'=> $systemlogs->where("type",'success')->count()
        ];

        // 下载器中已启用和未启动数量
        $downloadsData = [
            'activeCount' => $downloads->where('status','1')->count(),
            'noactiveCount' => $downloads->where('status','0')->count(),
        ];
        
        // 站点中已配置passkey和未配置passkey数量
        $sitesData = [
            'activeCount' =>  $sites->where('passkey','<>','')->count(),
            'noactiveCount' => $sites->where('passkey','=','')->count(),
        ];
        // 获取种子库总数
        $bankTorrentData = [
            'count' => TorrentBank::where(1,1)->count()
        ];

        // 通过站点列表初始化一个数组，包含站点名称和已辅种种子数
        foreach ($sites as $key => $site) {
            $torrentCacheData[$key] = [
                'name' => $site->site_name,
                'count' => 0
            ];
        }

        // 进行判断已辅种数据库中对应站点数
        foreach ( $torrentscache as $key => $value) {
            foreach ($sites as $key2 => $value2) {
                if($value->sid == $value2->id){
                    $torrentCacheData[$key2]['count'] = $value2->count + 1;
                }
            }
        }
        
        // 获取计划任务数量已经总执行次数
        $crontabRunTimes = 0;
        foreach ($crontabs as $key => $crontab) {
            $crontabRunTimes = $crontabRunTimes + $crontab->running_times;
        }
        $crontabData = [
            'count' => $crontabs->count(),
            'runtime'=> $crontabRunTimes,
        ];

        $returnData = [
            'systemLog' => $systemLogsData,
            'download' => $downloadsData,
            'site' => $sitesData,
            'torrentbank' => $bankTorrentData,
            'torrentcache' => $torrentCacheData,
            'crontab' => $crontabData

        ];
        return json(['code'=>200,'msg'=> '获取成功','data'=> $returnData]);
    }

}
